<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <!-- 实现页面的基本布局 -->
      <el-card class="tree-card">
        <!-- 用了一个行列布局 -->
        <treeTools
          :tree-node="company"
          isRoot
          @addDepts="addDeptsFn"
        ></treeTools>
        <!-- 下面就是树形控件内容了 -->
        <el-tree
          default-expand-all
          :data="departmentList"
          :props="defaultProps"
        >
          <!-- 注意：node是抛出来的当前的节点信息，data是当前的节点数据 -->
          <treeTools
            slot-scope="{ data }"
            :tree-node="data"
            @addDepts="addDeptsFn"
            @editDepts="editDeptsFn"
            @success="initData"
          ></treeTools>
        </el-tree>
      </el-card>
    </div>
    <!-- 新增部门弹框 -->
    <addDepts
      ref="dialog"
      :dialog-visible.sync="addDialogShow"
      :tree-node="node"
      @success="initData"
    ></addDepts>
  </div>
</template>

<script>
import treeTools from './components/tree-tools'
import addDepts from './components/add-depts'
import { getDepartmentApi } from '@/api/department'
import { tranListToTreeData } from '@/utils'
export default {
  components: {
    treeTools,
    addDepts
  },
  data() {
    return {
      departmentList: [], // 存放组织架构树形数据
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      company: {}, // 顶级节点的数据信息
      addDialogShow: false, // 控制弹框的显示与隐藏
      node: {}, // 存储当前节点信息
      loading: false
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 编辑部门
    async editDeptsFn(node) {
      this.node = node
      this.addDialogShow = true
      await this.$nextTick()
      this.$refs.dialog.getDepartmentInfo()
    },
    // 新增部门
    addDeptsFn(node) {
      // 将当前的节点信息存储起来，供弹框使用
      this.node = node
      this.addDialogShow = true
    },
    // 初始化部门列表数据
    async initData() {
      this.loading = true
      try {
        const { depts, companyName } = await getDepartmentApi()
        this.departmentList = tranListToTreeData(depts, '')
        this.company = { name: companyName, manager: '负责人' }
      } catch (error) {}
      this.loading = false
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
</style>
